//
//  BindBankViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/8/7.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "BindBankViewController.h"
#import "CountryListViewController.h"
#import "PaypalCustomAlert.h"
#import "PaypalModel.h"
#import "SC_ActionSheet.h"
#import <AliyunOSSiOS/OSSService.h>
@interface BindBankViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (strong, nonatomic) UIView *bgView;
@property (strong, nonatomic) UILabel *paypalClass;
@property (strong, nonatomic) UIImageView *choosePayPalIcon;
@property (strong, nonatomic) UILabel *payPalMessageLab;
@property (strong, nonatomic) UIButton *choosebutton;
@property (strong, nonatomic) NSMutableArray *dataArray;

@property (strong, nonatomic) UIView *bankView;
@property (strong, nonatomic) UITextField *openingField;
@property (strong, nonatomic) UITextField *branchField;
@property (strong, nonatomic) UITextField *bankNumberField;
//@property (strong, nonatomic) UITextField *reservedcellField;

@property (strong, nonatomic) UITextField *alipayNameField;
@property (strong, nonatomic) UITextField *alipayNumberField;
@property (strong, nonatomic) UIImageView *alipayImageView;
@property (strong, nonatomic) UIImageView *alipayaddImage;
@property (strong, nonatomic) UILabel *alipayaddlable;
@property (strong, nonatomic) UIView *alipayView;
@property (strong, nonatomic) UITextField *weChatNameField;
@property (strong, nonatomic) UITextField *weChatNumberField;
@property (strong, nonatomic) UIImageView *weChatImageView;
@property (strong, nonatomic) UIImageView *weChataddImage;
@property (strong, nonatomic) UILabel *weChataddlable;
@property (strong, nonatomic) UIView *WeChatView;

@property (nonatomic,strong) UIButton * addBankButton;
@property (nonatomic,strong) UILabel * paypalMessage;

@property (nonatomic,strong)OSSClient *client;
@property (nonatomic,strong)NSString *bucketname;
@property (nonatomic,strong)NSString *filename; //上传地址的名称
@property (nonatomic,assign)BOOL isbindWeChat; //是否绑定微信
@property (nonatomic,assign)BOOL isbindAlipay; //是否绑定支付宝
@end

@implementation BindBankViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self showLoadingAnimation];
    self.view.backgroundColor = [ZBLocalized sharedInstance].BgViewLightColor;
    [self initUI];
    [self getData];
    [self setOSS];
}
/*OSS上传图片设置*/
- (void)setOSS
{
    WeakSelf
    [self GETWithHost:@"" path:ossAuth param:@{} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"code"] integerValue] ==0)//成功
        {
            NSDictionary * dic = responseObject[@"result"];
            NSDictionary * credentials = dic[@"credentials"];
            NSString *endpoint = dic[@"endpoint"];
            self.bucketname = dic[@"bucket"];
            id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:credentials[@"access_key_id"] secretKeyId:credentials[@"access_key_secret"] securityToken:credentials[@"security_token"]];
            
            weakSelf.client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
            [self stopLoadingAnimation];
        }
        
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)getData
{
    NSArray * titles;
    NSArray * imgs;
    if ([[AppDelegate shareAppdelegate].privilages containsString:@"8"]) {
        
        titles = @[Localized(@"C2C_Bank_card"),Localized(@"OTC_alipay"),Localized(@"OTC_weChat")];
        imgs = @[@"otc_icon_card",@"otc_icon_zhi",@"otc_icon_vx"];
        
        
    } else {
        titles = @[Localized(@"C2C_Bank_card")];
        imgs = @[@"otc_icon_card"];
        
    }
    for (int i=0; i<imgs.count; i++)
    {
        PaypalModel * model = [[PaypalModel alloc] init];
        model.icon = imgs[i];
        model.title = titles[i];
        [self.dataArray addObject:model];
    }
    
    
    [self getLogsWithLogs:_dataAry];
    [self initPaypal:_index];
    
}
- (void)getLogsWithLogs:(NSArray *)Logs
{
    for (NSDictionary * dic in Logs)
    {
        if ([dic[@"status"] integerValue] ==1) //支付宝
        {
            [self getAlipaydata:dic];
        }else
        {
            [self getweChatdata:dic];
        }
    }
}
/*获取支付宝信息*/
- (void)getAlipaydata:(NSDictionary *)dic
{
    _alipayNameField.text = dic[@"name"];
    _alipayNumberField.text = dic[@"account"];
    [_alipayImageView sd_setImageWithURL:[NSURL URLWithString:dic[@"image"]]];
    _alipayaddlable.hidden = YES;
    _alipayaddImage.hidden = YES;
    _addBankButton.hidden = YES;
    _isbindAlipay = YES;
   
    _alipayImageView.mj_y = _alipayNumberField.bottom +RealValue_W(56);
}
/*获取微信信息*/
- (void)getweChatdata:(NSDictionary *)dic
{
    _weChatNameField.text = dic[@"name"];
    _weChatNumberField.text = dic[@"account"];
    [_weChatImageView sd_setImageWithURL:[NSURL URLWithString:dic[@"image"]]];
    _weChataddlable.hidden = YES;
    _weChataddImage.hidden = YES;
    _isbindWeChat = YES;
    _addBankButton.hidden = YES;
    _weChatImageView.mj_y = _weChatNumberField.bottom +RealValue_W(56);
    
}
- (void)initPaypal:(NSInteger)index
{
    _index = index;
    switch (index) {
        case 0:
            [self choosebank];
            break;
        case 1:
            [self chooseAlipay];
            break;
        case 2:
            [self chooseWeChat];
            break;
            
        default:
            break;
    }
}
- (void)initUI
{
    [self.view addSubview:self.bgView];
    [_bgView addSubview:self.paypalClass];
    [_bgView addSubview:self.choosePayPalIcon];
    [_bgView addSubview:self.payPalMessageLab];
    [_bgView addSubview:self.choosebutton];
    [_bgView addSubview:self.bankView];
    [self initTextField];
    [_bgView addSubview:self.WeChatView];
    [self initWithWeChat];
    [_bgView addSubview:self.alipayView];
    [self initWithalipay];
    [self.view addSubview:self.addBankButton];
    if ([[AppDelegate shareAppdelegate].privilages containsString:@"8"]) {
        
        [self.view addSubview:self.paypalMessage];
        
    }
    
    
}
- (void)initWithalipay
{
    NSArray * titles = @[Localized(@"OTC_add_paypal_message"),Localized(@"OTC_paypal_number_message")];
    for (int i=0; i<titles.count; i++)
    {
        UITextField * textField = [[UITextField alloc]initWithFrame:CGRectMake(RealValue_W(60),
                                                                               RealValue_W(40) + i *RealValue_W(110),
                                                                               UIScreenWidth - RealValue_W(120),
                                                                               RealValue_W(60))];
        textField.textAlignment=NSTextAlignmentLeft;
        textField.backgroundColor = [UIColor clearColor];
        textField.placeholder = titles[i];
        textField.tintColor = TABTITLECOLOR;
        [textField setValue:textFieldPCOLOR forKeyPath:@"_placeholderLabel.textColor"];
        [textField setValue:AutoFont(13)forKeyPath:@"_placeholderLabel.font"];
        textField.font = AutoBoldFont(13);
        textField.textColor = MAINTITLECOLOR;
        UIBezierPath * bezierPath = [UIBezierPath bezierPath];
        [bezierPath moveToPoint:CGPointMake(RealValue_W(60) ,textField.bottom + RealValue_W(20))];
        [bezierPath addLineToPoint:CGPointMake(self.view.width - RealValue_W(60) ,textField.bottom + RealValue_W(20))];
        CAShapeLayer * shapeLayer = [CAShapeLayer layer];
        shapeLayer.strokeColor = CELLCOLOR.CGColor;
        shapeLayer.fillColor  = [UIColor clearColor].CGColor;
        shapeLayer.path = bezierPath.CGPath;
        shapeLayer.lineWidth = 0.5f;
        [_alipayView.layer addSublayer:shapeLayer];
        if (i == 0)
        {
            _alipayNameField = textField;
        }else if (i == 1)
        {
            _alipayNumberField = textField ;
        }
        
        [_alipayView addSubview:textField];
    }
    [_alipayView addSubview:self.alipayImageView];
    [_alipayImageView addSubview:self.alipayaddImage];
    [_alipayImageView addSubview:self.alipayaddlable];
}
- (void)initWithWeChat
{
     NSArray * titles = @[Localized(@"OTC_add_paypal_message"),Localized(@"OTC_weChat_number_message")];
    for (int i=0; i<titles.count; i++)
    {
        UITextField * textField = [[UITextField alloc]initWithFrame:CGRectMake(RealValue_W(60),
                                                                               RealValue_W(40) + i *RealValue_W(110),
                                                                               UIScreenWidth - RealValue_W(120),
                                                                               RealValue_W(60))];
        textField.textAlignment=NSTextAlignmentLeft;
        textField.backgroundColor = [UIColor clearColor];
        textField.placeholder = titles[i];
        textField.tintColor = TABTITLECOLOR;
        [textField setValue:textFieldPCOLOR forKeyPath:@"_placeholderLabel.textColor"];
        [textField setValue:AutoFont(13)forKeyPath:@"_placeholderLabel.font"];
        textField.font = AutoBoldFont(13);
        textField.textColor = MAINTITLECOLOR;
        UIBezierPath * bezierPath = [UIBezierPath bezierPath];
        [bezierPath moveToPoint:CGPointMake(RealValue_W(60) ,textField.bottom + RealValue_W(20))];
        [bezierPath addLineToPoint:CGPointMake(self.view.width - RealValue_W(60) ,textField.bottom + RealValue_W(20))];
        CAShapeLayer * shapeLayer = [CAShapeLayer layer];
        shapeLayer.strokeColor = CELLCOLOR.CGColor;
        shapeLayer.fillColor  = [UIColor clearColor].CGColor;
        shapeLayer.path = bezierPath.CGPath;
        shapeLayer.lineWidth = 0.5f;
        [_WeChatView.layer addSublayer:shapeLayer];
        if (i == 0)
        {
            _weChatNameField = textField;
        }else if (i == 1)
        {
            _weChatNumberField = textField ;
        }
        
        [_WeChatView addSubview:textField];
    }
    [_WeChatView addSubview:self.weChatImageView];
    [_weChatImageView addSubview:self.weChataddImage];
    [_weChatImageView addSubview:self.weChataddlable];
}
- (void)initTextField
{
    NSArray * titles = @[Localized(@"Opening_bank_message"),Localized(@"Account_opening_branch_message"),Localized(@"Bank_card_number_message")];
    for (int i=0; i<titles.count; i++)
    {
        UITextField * textField = [[UITextField alloc]initWithFrame:CGRectMake(RealValue_W(60),
                                                                                RealValue_W(40) + i *RealValue_W(110),
                                                                              UIScreenWidth - RealValue_W(120),
                                                                               RealValue_W(60))];
        textField.textAlignment=NSTextAlignmentLeft;
        textField.backgroundColor = [UIColor clearColor];
        textField.placeholder = titles[i];
        textField.tintColor = TABTITLECOLOR;
        [textField setValue:textFieldPCOLOR forKeyPath:@"_placeholderLabel.textColor"];
        [textField setValue:AutoFont(13)forKeyPath:@"_placeholderLabel.font"];
        textField.font = AutoBoldFont(13);
        textField.textColor = MAINTITLECOLOR;
        UIBezierPath * bezierPath = [UIBezierPath bezierPath];
        [bezierPath moveToPoint:CGPointMake(RealValue_W(60) ,textField.bottom + RealValue_W(20))];
        [bezierPath addLineToPoint:CGPointMake(self.view.width - RealValue_W(60) ,textField.bottom + RealValue_W(20))];
        CAShapeLayer * shapeLayer = [CAShapeLayer layer];
        shapeLayer.strokeColor = CELLCOLOR.CGColor;
        shapeLayer.fillColor  = [UIColor clearColor].CGColor;
        shapeLayer.path = bezierPath.CGPath;
        shapeLayer.lineWidth = 0.5f;
        [_bankView.layer addSublayer:shapeLayer];
        if (i == 0)
        {
           _openingField = textField ;
        }else if (i == 1)
        {
           _branchField=textField;
        }else if (i == 2)
        {
            _bankNumberField =textField;
            textField.keyboardType =  UIKeyboardTypeNumberPad;
        }
        [_bankView addSubview:textField];
    }
    
    
}
#pragma make  选择支付方式
- (void)choosePaypalWithButton:(UIButton *)button
{
    WeakSelf
    CountryListViewController * custom = [[CountryListViewController alloc] initWithCustomContentViewClass:@"PaypalCustomAlert" delegate:nil];
    custom.direction = FromBottom;
    [custom showWith:self.dataArray wihtISSell:NO];

    PaypalCustomAlert *aleatView = (PaypalCustomAlert *)custom.contentView;
    aleatView.index = _index;
    aleatView.cancelBlock = ^{
        [custom dismiss];
    };
    aleatView.selectIndexPathRow = ^(NSInteger index,NSString*capital) {
       [weakSelf initPaypal:index];
       [custom dismiss];
    };
    
}
- (void)choosebank
{
    _bankView.hidden = NO;
    _alipayView.hidden = YES;
    _WeChatView.hidden = YES;
    _addBankButton.hidden = NO;
    _paypalClass.attributedText = [EXUnit getcontent:[NSString stringWithFormat:@"  %@",Localized(@"C2C_Bank_card")] image:@"otc_icon_card" index:0 imageframe:CGRectMake(0, -2, RealValue_W(28), RealValue_W(28))];
    
//    RACSignal*opening=[_openingField.rac_textSignal map:^id(NSString* value) {
//        return @(value.length>0);
//    }];
//    RACSignal*branch=[_branchField.rac_textSignal map:^id(NSString* value) {
//        return @(value.length>0);
//    }];
//    RACSignal*bankNumber=[_bankNumberField.rac_textSignal map:^id(NSString* value) {
//        return @(value.length>0);
//    }];
//    RACSignal*loginSignal=[RACSignal combineLatest:@[opening,branch,bankNumber] reduce:^id(NSNumber*openingValid,NSNumber*branchValid,NSNumber*bankNumberValid)
//                           {
//                               return @([openingValid boolValue]&&[branchValid boolValue]&&[bankNumberValid boolValue]);
//                           }];
//    [loginSignal subscribeNext:^(NSNumber* x) {
//        if ([x boolValue]) {
//            self.addBankButton.enabled=YES;
//            self.addBankButton.alpha = 1;
//        }else{
//            self.addBankButton.enabled=NO;
//            self.addBankButton.alpha = 0.5;
//
//        }
//    }];

}
- (void)chooseAlipay
{
    _bankView.hidden = YES;
    _alipayView.hidden = NO;
    _WeChatView.hidden = YES;
    if (_isbindAlipay) {
         _addBankButton.hidden = YES;
    }else
    {
        _addBankButton.hidden = NO;
    }
    _paypalClass.attributedText = [EXUnit getcontent:[NSString stringWithFormat:@"  %@",Localized(@"OTC_alipay")] image:@"otc_icon_zhi" index:0 imageframe:CGRectMake(0, -2, RealValue_W(28), RealValue_W(28))];
//    RACSignal*alipayName=[_alipayNameField.rac_textSignal map:^id(NSString* value) {
//        return @(value.length>0);
//    }];
//    RACSignal*alipayNumber=[_alipayNumberField.rac_textSignal map:^id(NSString* value) {
//        return @(value.length>0);
//    }];
//
//    RACSignal*loginSignal=[RACSignal combineLatest:@[alipayName,alipayNumber] reduce:^id(NSNumber*alipayNameValid,NSNumber*alipayNumberValid)
//                           {
//                               return @([alipayNameValid boolValue]&&[alipayNumberValid boolValue]);
//                           }];
//    [loginSignal subscribeNext:^(NSNumber* x) {
//        if ([x boolValue]) {
//            self.addBankButton.enabled=YES;
//            self.addBankButton.alpha = 1;
//        }else{
//            self.addBankButton.enabled=NO;
//            self.addBankButton.alpha = 0.5;
//
//        }
//    }];
}
- (void)chooseWeChat
{
    _bankView.hidden = YES;
    _alipayView.hidden = YES;
    _WeChatView.hidden = NO;
    _paypalClass.attributedText = [EXUnit getcontent:[NSString stringWithFormat:@"  %@",Localized(@"OTC_weChat")]  image:@"otc_icon_vx" index:0 imageframe:CGRectMake(0, -2, RealValue_W(28), RealValue_W(28))];
    if (_isbindWeChat) {
        _addBankButton.hidden = YES;
    }else
    {
        _addBankButton.hidden = NO;
    }
//    RACSignal*weChatName=[_weChatNameField.rac_textSignal map:^id(NSString* value) {
//        return @(value.length>0);
//    }];
//    RACSignal*weChatNumber=[_weChatNumberField.rac_textSignal map:^id(NSString* value) {
//        return @(value.length>0);
//    }];
//
//    RACSignal*loginSignal=[RACSignal combineLatest:@[weChatName,weChatNumber] reduce:^id(NSNumber*weChatNameValid,NSNumber*weChatNumberValid)
//                           {
//                               return @([weChatNameValid boolValue]&&[weChatNumberValid boolValue]);
//                           }];
//    [loginSignal subscribeNext:^(NSNumber* x) {
//        if ([x boolValue]) {
//            self.addBankButton.enabled=YES;
//            self.addBankButton.alpha = 1;
//        }else{
//            self.addBankButton.enabled=NO;
//            self.addBankButton.alpha = 0.5;
//
//        }
//    }];
}
#pragma make ---懒加载
- (UIView *)bgView
{
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, UIScreenWidth, UIScreenHeight -kStatusBarAndNavigationBarHeight)];
        _bgView.backgroundColor = TABLEVIEWLCOLOR;
        _bgView.userInteractionEnabled = YES;
        UIBezierPath * bezierPath = [UIBezierPath bezierPath];
        [bezierPath moveToPoint:CGPointMake(RealValue_W(60) , RealValue_W(120))];
        [bezierPath addLineToPoint:CGPointMake(self.view.width - RealValue_W(60) , RealValue_W(120))];
        CAShapeLayer * shapeLayer = [CAShapeLayer layer];
        shapeLayer.strokeColor = CELLCOLOR.CGColor;
        shapeLayer.fillColor  = [UIColor clearColor].CGColor;
        shapeLayer.path = bezierPath.CGPath;
        shapeLayer.lineWidth = 0.5f;
        [_bgView.layer addSublayer:shapeLayer];
    }
    return _bgView;
}
- (UILabel *)paypalClass
{
    if (!_paypalClass) {
        _paypalClass = [[UILabel alloc] initWithFrame:CGRectMake(RealValue_W(60), RealValue_W(40), 120, RealValue_W(40))];
        _paypalClass.textColor = MAINTITLECOLOR;
        _paypalClass.font = AutoBoldFont(15);
       
    }
    return _paypalClass;
}

- (UIImageView *)choosePayPalIcon
{
    if (!_choosePayPalIcon) {
        _choosePayPalIcon = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.width -  RealValue_W(28) - RealValue_W(10), 0  ,  RealValue_W(10), RealValue_W(16))];
        _choosePayPalIcon.image = [UIImage imageNamed:@"icon_list_go"];
        _choosePayPalIcon.centerY = _paypalClass.centerY;
    }
    return _choosePayPalIcon;
}
- (UILabel *)payPalMessageLab
{
    if (!_payPalMessageLab) {
        _payPalMessageLab = [[UILabel alloc] initWithFrame:CGRectMake(UIScreenWidth - 130 - RealValue_W(38), 0, 120, RealValue_W(32))];
        _payPalMessageLab.textColor = MAINTITLECOLOR1;
        _payPalMessageLab.font = AutoFont(12);
        _payPalMessageLab.textAlignment = NSTextAlignmentRight;
        
        _payPalMessageLab.text = Localized(@"OTC_Payment_Method");
        _payPalMessageLab.centerY = _choosePayPalIcon.centerY;
    }
    return _payPalMessageLab;
}
- (UIButton *)choosebutton
{
    WeakSelf
    if (!_choosebutton) {
        _choosebutton = [UIButton dd_buttonSystemButtonWithFrame:CGRectMake(0, 10, self.view.width, RealValue_W(98)) NormalBackgroundImageString:@"" tapAction:^(UIButton *button) {
            
            [weakSelf choosePaypalWithButton:button];
        }];
    }
    return _choosebutton;
}
- (UIImageView *)weChatImageView
{
    if (!_weChatImageView) {
        _weChatImageView = [[UIImageView alloc] initWithFrame:CGRectMake(RealValue_W(60), _weChatNumberField.bottom +RealValue_W(56), UIScreenWidth -RealValue_W(120) , RealValue_W(398))];
        _weChatImageView.backgroundColor = [ZBLocalized sharedInstance].paymentimageViewColor;
        UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(certificatestapAction)];
        _weChatImageView.userInteractionEnabled = YES;
        [_weChatImageView addGestureRecognizer:tapGesturRecognizer];
    }
    return _weChatImageView;
}
- (UIImageView *)weChataddImage
{
    if (!_weChataddImage) {
        _weChataddImage = [[UIImageView alloc] initWithFrame:CGRectMake(_weChatImageView.width/2 - RealValue_W(126)/2, RealValue_W(100), RealValue_W(126) , RealValue_W(126))];
        _weChataddImage.image = [UIImage imageNamed:[ZBLocalized sharedInstance].paymentimage];
    }
    return _weChataddImage;
}
- (UILabel *)weChataddlable
{
    if (!_weChataddlable) {
        _weChataddlable = [[UILabel alloc] initWithFrame:CGRectMake(0, _weChataddImage.bottom + 20, _weChatImageView.width, RealValue_W(32))];
        _weChataddlable.textColor = MAINTITLECOLOR1;
        _weChataddlable.font = AutoFont(15);
        _weChataddlable.textAlignment = NSTextAlignmentCenter;
        _weChataddlable.centerX = _weChataddImage.centerX;
        _weChataddlable.text = Localized(@"OTC_weChat_image_message");
        
    }
    return _weChataddlable;
}
- (UIImageView *)alipayImageView
{
    if (!_alipayImageView) {
        _alipayImageView = [[UIImageView alloc] initWithFrame:CGRectMake(RealValue_W(60), _alipayNumberField.bottom +RealValue_W(56), UIScreenWidth -RealValue_W(120) , RealValue_W(398))];
        _alipayImageView.backgroundColor = [ZBLocalized sharedInstance].paymentimageViewColor;
        UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(alipayImageAction)];
        _alipayImageView.userInteractionEnabled = YES;
        [_alipayImageView addGestureRecognizer:tapGesturRecognizer];
    }
    return _alipayImageView;
}
- (UIImageView *)alipayaddImage
{
    if (!_alipayaddImage) {
        _alipayaddImage = [[UIImageView alloc] initWithFrame:CGRectMake(_weChatImageView.width/2 - RealValue_W(126)/2, RealValue_W(100), RealValue_W(126) , RealValue_W(126))];
        _alipayaddImage.image = [UIImage imageNamed:[ZBLocalized sharedInstance].paymentimage];
    }
    return _alipayaddImage;
}
- (UILabel *)alipayaddlable
{
    if (!_alipayaddlable) {
        _alipayaddlable = [[UILabel alloc] initWithFrame:CGRectMake(0, _weChataddImage.bottom + 20, _weChatImageView.width, RealValue_W(32))];
        _alipayaddlable.textColor = MAINTITLECOLOR1;
        _alipayaddlable.font = AutoFont(15);
        _alipayaddlable.textAlignment = NSTextAlignmentCenter;
        _alipayaddlable.centerX = _weChataddImage.centerX;
        _alipayaddlable.text = Localized(@"OTC_paypalt_image_message");
        
    }
    return _alipayaddlable;
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray new];
    }
    return _dataArray;
}
- (UIView *)bankView
{
    if (!_bankView) {
        _bankView = [[UIView alloc] initWithFrame:CGRectMake(0, RealValue_W(122), UIScreenWidth, UIScreenHeight)];
        _bankView.backgroundColor = TABLEVIEWLCOLOR;
    }
    return _bankView;
}
- (UIView *)alipayView
{
    if (!_alipayView) {
        _alipayView = [[UIView alloc] initWithFrame:CGRectMake(0, RealValue_W(122), UIScreenWidth, UIScreenHeight)];
        _alipayView.backgroundColor = TABLEVIEWLCOLOR;
    }
    return _alipayView;
}
- (UIView *)WeChatView
{
    if (!_WeChatView) {
        _WeChatView = [[UIView alloc] initWithFrame:CGRectMake(0, RealValue_W(122), UIScreenWidth, UIScreenHeight)];
        _WeChatView.backgroundColor = TABLEVIEWLCOLOR;
    }
    return _WeChatView;
}
- (UIButton *)addBankButton
{
    if (!_addBankButton) {
        _addBankButton = [[UIButton alloc] initWithFrame:CGRectMake(RealValue_W(30), UIScreenHeight -85  - kStatusBarAndNavigationBarHeight - IPhoneBottom, UIScreenWidth - RealValue_W(60), 40)];
        _addBankButton.backgroundColor = TABTITLECOLOR;
        
        [_addBankButton addTarget:self action:@selector(next:) forControlEvents:UIControlEventTouchUpInside];
        [_addBankButton setTitle:Localized(@"Security_Next_step") forState:0];
        _addBankButton.titleLabel.font = AutoBoldFont(15);
        [_addBankButton setTitleColor:WHITECOLOR forState:0];
    }
    return _addBankButton;
}
- (UILabel *)paypalMessage
{
    if (!_paypalMessage) {
        _paypalMessage = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 40)];
        _paypalMessage.textColor = MAINTITLECOLOR1;
        _paypalMessage.font = AutoFont(13);
        _paypalMessage.text = Localized(@"OTC_Income_Payment_message");
        _paypalMessage.numberOfLines = 0;
        _paypalMessage.bottom = _addBankButton.mj_y -10;
        _paypalMessage.centerX = self.view.centerX;
    }
    return _paypalMessage;
}
- (void)next:(UIButton *)sender {
    
    switch (_index) {
        case 0:
            {
                [self bindbank];
            }
            break;
        case 1:
        {
            [self bindAlipay];
        }
            break;
        case 2:
        {
            [self bindWeChat];
        }
            break;
            
        default:
            break;
    }
    
   
}
/*绑定银行卡*/
- (void)bindbank
{
  
    if (![EXUnit judgebankNumberLegal:_bankNumberField.text]) {

        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"C2C_bank_card_format_error") view:kWindow];
        return;

    }
    if ([NSString isEmptyString:_openingField.text]) {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Opening_bank_message") view:kWindow];
        return;
    }
    if ([NSString isEmptyString:_branchField.text]) {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Account_opening_branch_message") view:kWindow];
        return;
    }
    [_openingField resignFirstResponder];
    [_branchField resignFirstResponder];
    [_bankNumberField resignFirstResponder];
    CustomAlertVC * custom = [[CustomAlertVC alloc] initWithCustomContentViewClass:@"BindCustonAlert" delegate:nil];
    custom.direction = FromBottom;
    [custom show];
    BindCustonAlert *aleatView = (BindCustonAlert *)custom.contentView;
    aleatView.type = @"12";
    aleatView.isBindGoole = NO;
    aleatView.cancelBlock = ^{
        [custom dismiss];
    };
    WeakSelf
    WeakObject(aleatView)
    [aleatView.okButton add_BtnClickHandler:^(NSInteger tag) {
        
        
        
        if (![NSString isEmptyString:weakaleatView.emailField.text])
        {
            if (![EXUnit CodeissSixplace:weakaleatView.emailField.text]) {
                [EXUnit showMessage:Localized(@"VerificationMessage")];
                [weakaleatView.okButton stopAnimation];
                return ;
            }
        }
        if (![NSString isEmptyString:weakaleatView.phoneField.text])
        {
            if (![EXUnit CodeissSixplace:weakaleatView.phoneField.text]) {
                [EXUnit showMessage:Localized(@"VerificationMessage")];
                [weakaleatView.okButton stopAnimation];
                return ;
            }
        }
        NSDictionary * param = @{@"bank_name":[EXUnit removeStrCharacter:weakSelf.openingField.text],
                                 @"sub_bank_name":[EXUnit removeStrCharacter:weakSelf.branchField.text],
                                 @"number":[EXUnit removeStrCharacter:weakSelf.bankNumberField.text],
                                 @"pre_phone":@"",
                                 @"sms_code":[NSString isEmptyString:weakaleatView.phoneField.text]?@"":weakaleatView.phoneField.text,
                                 @"email_code":[NSString isEmptyString:weakaleatView.emailField.text]?@"":weakaleatView.emailField.text,
                                 @"two_step_code":[NSString isEmptyString:weakaleatView.gooldField.text]?@"":weakaleatView.gooldField.text};
        
        [weakSelf POSTWithHost:@"" path:Binduserbank param:param cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [weakaleatView.okButton stopAnimation];
            if ([responseObject[@"code"] integerValue]==0)//成功
            {
                [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
                [[NSNotificationCenter defaultCenter] postNotificationName:bindbnakNotificationse object:@{@"type":@"0"}];
                [custom dismiss];
                [self.navigationController popViewControllerAnimated:YES];
                
            }else
            {
                [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
            }
            
        } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [weakaleatView.okButton stopAnimation];
            
        }];
        
    }];
    
   
}
/*绑定支付宝*/
- (void)bindAlipay
{
    if ([NSString isEmptyString:_filename]) {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"OTC_paypalt_image_message1") view:kWindow];
        return;
    }
    if ([NSString isEmptyString:_alipayNameField.text]) {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"OTC_add_paypal_message") view:kWindow];
        return;
    }
    if ([NSString isEmptyString:_alipayNumberField.text]) {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"OTC_paypal_number_message") view:kWindow];
        return;
    }
    [_alipayNameField resignFirstResponder];
    [_alipayNumberField resignFirstResponder];
    CustomAlertVC * custom = [[CustomAlertVC alloc] initWithCustomContentViewClass:@"BindCustonAlert" delegate:nil];
    custom.direction = FromBottom;
    [custom show];
    BindCustonAlert *aleatView = (BindCustonAlert *)custom.contentView;
    aleatView.type = @"12";
    aleatView.isBindGoole = NO;
    aleatView.cancelBlock = ^{
        [custom dismiss];
    };
    WeakSelf
    WeakObject(aleatView)
    [aleatView.okButton add_BtnClickHandler:^(NSInteger tag) {

        if (![NSString isEmptyString:weakaleatView.emailField.text])
        {
            if (![EXUnit CodeissSixplace:weakaleatView.emailField.text]) {
                [EXUnit showMessage:Localized(@"VerificationMessage")];
                 [weakaleatView.okButton stopAnimation];
                return ;
            }
        }
        if (![NSString isEmptyString:weakaleatView.phoneField.text])
        {
            if (![EXUnit CodeissSixplace:weakaleatView.phoneField.text]) {
                [EXUnit showMessage:Localized(@"VerificationMessage")];
                 [weakaleatView.okButton stopAnimation];
                return ;
            }
        }
        NSDictionary * param = @{@"name":[EXUnit removeStrCharacter:weakSelf.alipayNameField.text],
                                 @"account":[EXUnit removeStrCharacter:weakSelf.alipayNumberField.text],
                                 @"filename":weakSelf.filename,
                                 @"status":@"1",
                                 @"withdraw_password":@"",
                                 @"sms_code":[NSString isEmptyString:weakaleatView.phoneField.text]?@"":weakaleatView.phoneField.text,
                                 @"email_code":[NSString isEmptyString:weakaleatView.emailField.text]?@"":weakaleatView.emailField.text,
                                 @"two_step_code":[NSString isEmptyString:weakaleatView.gooldField.text]?@"":weakaleatView.gooldField.text};
        
        [weakSelf POSTWithHost:@"" path:addMobilePay param:param cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [weakaleatView.okButton stopAnimation];
            if ([responseObject[@"code"] integerValue]==0)//成功
            {
                [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
                [[NSNotificationCenter defaultCenter] postNotificationName:bindbnakNotificationse object:@{@"type":@"1"}];
                [custom dismiss];
                [self.navigationController popViewControllerAnimated:YES];
                
            }else
            {
                [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
            }
            
        } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [weakaleatView.okButton stopAnimation];
            
        }];
        
    }];
}
/*绑定微信*/
- (void)bindWeChat
{
    if ([NSString isEmptyString:_filename]) {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"OTC_weChat_image_message1") view:kWindow];
    }
    if ([NSString isEmptyString:_weChatNumberField.text]) {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"OTC_add_paypal_message") view:kWindow];
        return;
    }
    if ([NSString isEmptyString:_weChatNameField.text]) {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"OTC_paypal_number_message") view:kWindow];
        return;
    }
    [_weChatNumberField resignFirstResponder];
    [_weChatNameField resignFirstResponder];
    CustomAlertVC * custom = [[CustomAlertVC alloc] initWithCustomContentViewClass:@"BindCustonAlert" delegate:nil];
    custom.direction = FromBottom;
    [custom show];
    BindCustonAlert *aleatView = (BindCustonAlert *)custom.contentView;
    aleatView.type = @"12";
    aleatView.isBindGoole = NO;
    aleatView.cancelBlock = ^{
        [custom dismiss];
    };
    WeakSelf
    WeakObject(aleatView)
    [aleatView.okButton add_BtnClickHandler:^(NSInteger tag) {
        
        if (![NSString isEmptyString:weakaleatView.emailField.text])
        {
            if (![EXUnit CodeissSixplace:weakaleatView.emailField.text]) {
                [EXUnit showMessage:Localized(@"VerificationMessage")];
                 [weakaleatView.okButton stopAnimation];
                return ;
            }
        }
        if (![NSString isEmptyString:weakaleatView.phoneField.text])
        {
            if (![EXUnit CodeissSixplace:weakaleatView.phoneField.text]) {
                [EXUnit showMessage:Localized(@"VerificationMessage")];
                 [weakaleatView.okButton stopAnimation];
                return ;
            }
        }
        NSDictionary * param = @{@"name":[EXUnit removeStrCharacter:weakSelf.weChatNameField.text],
                                 @"account":[EXUnit removeStrCharacter:weakSelf.weChatNumberField.text],
                                 @"filename":weakSelf.filename,
                                 @"status":@"2",
                                 @"withdraw_password":@"",
                                 @"sms_code":[NSString isEmptyString:weakaleatView.phoneField.text]?@"":weakaleatView.phoneField.text,
                                 @"email_code":[NSString isEmptyString:weakaleatView.emailField.text]?@"":weakaleatView.emailField.text,
                                 @"two_step_code":[NSString isEmptyString:weakaleatView.gooldField.text]?@"":weakaleatView.gooldField.text};
        
        [weakSelf POSTWithHost:@"" path:addMobilePay param:param cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [weakaleatView.okButton stopAnimation];
            if ([responseObject[@"code"] integerValue]==0)//成功
            {
                [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
                [[NSNotificationCenter defaultCenter] postNotificationName:bindbnakNotificationse object:@{@"type":@"2"}];
                [custom dismiss];
                [self.navigationController popViewControllerAnimated:YES];
                
            }else
            {
                [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
            }
            
        } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [weakaleatView.okButton stopAnimation];
            
        }];
        
    }];
}
/*上传微信照片*/
- (void)certificatestapAction
{
     [self uploadImage];
}
/*支付宝上传照片*/
- (void)alipayImageAction
{
    [self uploadImage];
    
}
- (void)uploadImage
{
    WeakSelf
    SC_ActionSheet *sheet = [[SC_ActionSheet alloc]initWithFirstTitle:Localized(@"Authentication_Photograph_message") secondTitle:Localized(@"Authentication_albums_message")];
    sheet.selectedSth = ^(NSInteger tag) {
        
        
        switch (tag) {
            case 0:
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    
                    UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
                    imagePicker.delegate = self;
                    imagePicker.allowsEditing = NO;
                    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                    [weakSelf presentViewController:imagePicker animated:YES completion:nil];
                }
                break;
            case 1:
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
                    UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
                    imagePicker.delegate = self;
                    imagePicker.allowsEditing = NO;
                    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                    [weakSelf presentViewController:imagePicker animated:YES completion:nil];
                }
                break;
            default:
                break;
        }
        
    };
    [sheet show];
}
#pragma mark 调用系统相册及拍照功能实现方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    UIImage * chosenImage = info[UIImagePickerControllerOriginalImage];
    
    //    chosenImage = [self imageWithImageSimple:chosenImage scaledToSize:CGSizeMake(400, 400)];
    
    
    
    //将图片上传到服务器
    
    [picker dismissViewControllerAnimated:YES completion:^{
        NSData * imageData = UIImageJPEGRepresentation(chosenImage, 1.0);
        [self uploadossimagedata:imageData image:chosenImage];
    }];
    
}

//上传图片
-(void)uploadossimagedata:(NSData*)data image:(UIImage *)image
{
    //显示加载标题
    [SVProgressHUD showWithStatus:Localized(@"Authentication_uploading_message")];
    //设置HUD和文本的颜色
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    //设置HUD背景颜色
    [SVProgressHUD setBackgroundColor:BLACKCOLOR];
    [SVProgressHUD setDefaultAnimationType:(SVProgressHUDAnimationTypeFlat)];
    
    
    
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName =self.bucketname;
    put.objectKey = [self getTimeNow];
    put.uploadingData = data; // 直接上传NSData
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    OSSTask * putTask = [_client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSString *object = put.objectKey;
            [self uploadImageWihtimageFile:object image:image];
        } else {
            [SVProgressHUD dismiss];
            [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Authentication_uploading_error_message") view:kWindow];
        }
        return nil;
    }];
    //     可以等待任务完成
    //    [putTask waitUntilFinished];
    
}
- (void)uploadImageWihtimageFile:(NSString *)file image:(UIImage *)image
{
   WeakSelf
    if (_index ==2)
    {
       
        dispatch_async(dispatch_get_main_queue(), ^{
            
            weakSelf.weChatImageView.image = image;
            weakSelf.weChataddImage.hidden = YES;
            weakSelf.weChataddlable.hidden = YES;
        });
    }else
    {
       
        dispatch_async(dispatch_get_main_queue(), ^{
            
            weakSelf.alipayImageView.image = image;
            weakSelf.alipayaddImage.hidden = YES;
            weakSelf.alipayaddlable.hidden = YES;
        });
    }
     _filename = file;
     [SVProgressHUD dismiss];
   
}
/**
 *  返回当前时间用来上传图片的时间戳
 *
 *  @return getTimeNow
 */
-(NSString *)getTimeNow
{
    NSString* date;
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    int last = arc4random() % 10000;
    NSString *timeNow = [[NSString alloc] initWithFormat:@"%@%i.jpg", date,last];
    NSLog(@"%@.jpg", timeNow);
    NSString *userId = [EXUserManager personalData].id;
    if ([NSString isEmptyString:userId]) {
        userId = @"";
    }
    userId = [userId stringByAppendingString:timeNow];
    return userId;
}

@end
